package com.witframework.core;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;


/**
 *该类通过：
 *<pre>
 *&lt;context-param&gt;
 *		&lt;description&gt;Spring ApplicationContext配置文件&lt;/description&gt;
 *		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
 *		&lt;param-value&gt;classpath:classpath:/applicationcontext/applicationContext.xml&lt;/param-value&gt;
 *&lt;/context-param&gt;
 *</pre>
 *初始化WebApplicationContext实例，SpringBeanFactory通过该实例获取spring bean的实例
 *<P>
 * @author wuxinyang
 *
 */
public class ContextLoaderServlet extends HttpServlet{
	private ContextLoader contextLoader;
	private WebApplicationContext webApplicationContext=null;

	/**
	 * Initialize the root web application context.
	 */
	public void init() throws ServletException {
		webApplicationContext=(WebApplicationContext)getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		if(webApplicationContext==null){
			this.contextLoader = new ContextLoader();
			webApplicationContext=this.contextLoader.initWebApplicationContext(getServletContext());
		}
		BeanFactory.instance(webApplicationContext);
	}
	/**
	 * Return the ContextLoader used by this servlet.
	 */
	public ContextLoader getContextLoader() {
		return contextLoader;
	}
	/**
	 * Close the root web application context.
	 */
	public void destroy() {
		if (this.contextLoader != null) {
			this.contextLoader.closeWebApplicationContext(getServletContext());
		}
	}
	/**
	 * This should never even be called since no mapping to this servlet should
	 * ever be created in web.xml. That's why a correctly invoked Servlet 2.3
	 * listener is much more appropriate for initialization work ;-)
	 */
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		getServletContext().log(
				"Attempt to call service method on ContextLoaderServlet as [" +
				request.getRequestURI() + "] was ignored");
		response.sendError(HttpServletResponse.SC_BAD_REQUEST);

	}


	public String getServletInfo() {
		return "ContextLoaderServlet for Servlet API 2.2/2.3 " +
		    "(deprecated in favor of ContextLoaderListener for Servlet API 2.4)";
	}



}
